<script setup lang="ts">
import { ref } from 'vue'
import qrcode from 'qrcode'
import { ElMessage } from 'element-plus'

const qrText = ref('')
const qrcodeOpts = {
    type: 'svg',
    width: 200,
    height: 200,
    margin: 4,
    color: {
        dark: '#000000', // 前景色
        light: '#ffffff', // 背景色
    },
    // errorCorrectionLevel: 'H'  // 错误修正级别：L, M, Q, H
}

const createQrCode = () => {
    if (!qrText.value) {
        ElMessage({
            type: 'warning',
            message: '请输入内容',
        })
        return
    }
    const qrcodeContainer = document.getElementById('qrContainer')
    if (!qrcodeContainer) return
    qrcode.toString(
        qrText.value,
        qrcodeOpts,
        function (error: string, svg: string) {
            if (error) {
                ElMessage({
                    type: 'error',
                    message: `二维码生成失败\n${error}`,
                })
            } else {
                // 将生成的 SVG 放入 DOM 中
                qrcodeContainer.innerHTML = svg
                ElMessage({
                    type: 'success',
                    message: `二维码生成成功\n`,
                })
                qrText.value = ''
            }
        },
    )
}
</script>

<template>
    <div class="base-container qrcode">
        <div class="qr-container">
            <h3>文本生成二维码</h3>
            <div class="input-cont w-full">
                <ElInput placeholder="请输入文本" v-model="qrText" />
                <ElButton type="primary" @click="createQrCode">生成</ElButton>
            </div>
            <div class="qr-cont" id="qrContainer"></div>
        </div>
    </div>
</template>

<style scoped lang="scss">
.qrcode {
    display: flex;
    justify-content: center;
    align-items: center;

    .qr-container {
        min-width: 200px;
        width: 50%;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 16px;

        .input-cont {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .qr-cont {
            width: 200px;
            height: 200px;
            background-color: #282828;
        }
    }
}
</style>
